package com.hdl.servlet.user;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdl.entity.HdlUser;
import com.hdl.service.UserService;
import com.hdl.service.impl.UserServiceImpl;

/**
 * 
 * @author Administrator
 *
 */
@WebServlet("/login.let")
public class LoginServlet extends HttpServlet{

	private UserService service = new UserServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置字符编码
		request.setCharacterEncoding("utf-8");
				
		//获取参数map
		Map<String, String[]> map = request.getParameterMap();
		String auto_login = request.getParameter("auto_login");
		
				
		//封装对象
		HdlUser loginUser = new HdlUser();
		try {
			BeanUtils.populate(loginUser, map);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
				
				
		//调用业务逻辑层
		HdlUser user = service.login(loginUser);
		
		//创建ObjectMapper对象
		ObjectMapper mapper = new ObjectMapper();
		
		//写回json数据
		response.setContentType("application/json;charset=utf-8");
		Map<String,Object> m = new HashMap<String, Object>();
		if(user == null) {
			m.put("code", 1);
			m.put("msg", "用户名或密码不正确");
		}else if(user.getHdlUserStatus() == 1) {//锁定
			m.put("code", 2);
			m.put("msg", "用户名已被锁定，请激活");
		}else {
			//判断是否进行了自动登陆勾选
			if("on".equals(auto_login)) {
				Cookie cookie = new Cookie("auto_login",user.getHdlUserName()+"#"+user.getHdlUserPsd());
				cookie.setMaxAge(60*60*27*7);//七天有效期
				response.addCookie(cookie);
			}
			
			//将数据存储在session中
			request.getSession().setAttribute("user", user);
			m.put("code", 3);
		}
		mapper.writeValue(response.getOutputStream(), m);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}
